import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/location_repository/location_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_list_item_bean.dart';
import 'package:e_reception_flutter/ui/company/choose_city/choose_city_page.dart';
import 'package:e_reception_flutter/ui/company/choose_city/widgets/choose_city_tabs_and_pages_widget.dart';
import 'package:e_reception_flutter/ui/company/company_register/bean/company_register_upload_bean.dart';
import 'package:e_reception_flutter/ui/index/even/location_changed_event.dart';
import 'package:e_reception_flutter/utils/address_about_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';

import 'company_register_sms_code_widget.dart';

/// 企业注册-编辑集合组件
///
/// @author: zengxiangxi
/// @createTime: 1/5/21 2:24 PM
/// @specialDemand:
class CompanyRegisterEditsWidget extends StatefulWidget {
  final String type;
  final ValueNotifier<CompanyRegisterUploadBean> onChanged;

  const CompanyRegisterEditsWidget({Key key, this.onChanged, this.type}) : super(key: key);

  @override
  _CompanyRegisterEditsWidgetState createState() =>
      _CompanyRegisterEditsWidgetState();
}

class _CompanyRegisterEditsWidgetState
    extends State<CompanyRegisterEditsWidget> {
  Map<String, ChooseCityListItemBean> _resultLocationMap;

  TextEditingController _companyNickEditingController;
  TextEditingController _companyNameEditingController;
  TextEditingController _locationEditingController;
  TextEditingController _detailAddressEditingController;
  TextEditingController _nameEditingController;
  TextEditingController _phoneEditingController;
  TextEditingController _authCodeEditingController;

  CompanyRegisterUploadBean _uploadBean;

  String registrationType;

  String gpsFrist;

  @override
  void dispose() {
    _companyNickEditingController?.dispose();
    _companyNameEditingController?.dispose();
    _locationEditingController?.dispose();
    _detailAddressEditingController?.dispose();
    _nameEditingController?.dispose();
    _phoneEditingController?.dispose();
    _authCodeEditingController?.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    AmapRepository.getInstance().init();
    _resultLocationMap = Map<String, ChooseCityListItemBean>();
    registrationType = widget?.type;
    _locationEditingController = TextEditingController()
      ..addListener(() => _notifyChange());
    _companyNickEditingController = TextEditingController()
      ..addListener(() => _notifyChange());
    _companyNameEditingController = TextEditingController()
      ..addListener(() => _notifyChange());
    _detailAddressEditingController = TextEditingController()
      ..addListener(() => _notifyChange());
    _nameEditingController = TextEditingController()
      ..addListener(() => _notifyChange());
    _phoneEditingController = TextEditingController()
      ..addListener(() => _notifyChange());
    _authCodeEditingController = TextEditingController()
      ..addListener(() => _notifyChange());

    VgEventBus.global.streamController.stream.listen((event) {
      if (event is LocationChangedEvent) {
        print("收到gps更新的:" + event?.gps);
        if(StringUtils.isNotEmpty(event?.gps??"")){
          LatLngBean latLngBean = LatLngBean();
          latLngBean = event?.latLngBean;
          gpsFrist = event?.gps;
          gpsFrist = AddressAboutUtils.getLongitudeAndLatitude(latLngBean?.longitude?.toString(), latLngBean?.latitude?.toString());
        }
      }
    });
    VgLocation().requestSingleLocation((map) {
      var transResult = VgLocationUtils.transLocationToMap(map);
      if (transResult == null) {
        return;
      }
      _resultLocationMap = transResult;
      _setLocationEditingValue();
      _notifyChange();
      // _getGpsStr();
    });
    _type();
  }

  void _type(){
    if(widget?.type!=null){
      if(registrationType=="04" || registrationType=="00"){
        registrationType = "企业"; //国有企业//民营企业
      }
      if(registrationType == "02"){//党政机关
        registrationType = "单位";
      }
      // if(registrationType=="00"){
      //   registrationType = "民营企业";
      // }
      if(registrationType=="03"){//大中小学
        registrationType = "学校";
      }
      if(registrationType=="01"){//培训机构
        registrationType = "机构";
      }
    }

  }

  ///通知更新
  _notifyChange() {
    if (widget?.onChanged == null) {
      return;
    }
    if (_uploadBean == null) {
      _uploadBean = CompanyRegisterUploadBean();
    }
    _uploadBean.setValue(
      locaiton: _locationEditingController?.text?.trim(),
      locationMap: _resultLocationMap,
      companyNick: _companyNickEditingController?.text?.trim(),
      name: _nameEditingController?.text?.trim(),
      phone: _phoneEditingController?.text?.trim(),
      companyName: _companyNameEditingController?.text?.trim(),
      detailAddress: _detailAddressEditingController?.text?.trim(),
      authCode: _authCodeEditingController?.text?.trim(),
      gps: _getGpsStr()?.contains("null")?gpsFrist:_getGpsStr() ?? gpsFrist,
    );
    widget?.onChanged?.value = _uploadBean;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: const EdgeInsets.symmetric(horizontal: 25),
        child: _toMainColumnWidget());
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        //企业单位简称组件
        _EditTextWithTitleWidget(
          controller: _companyNickEditingController,
          title: "${registrationType ?? "企业"}简称",
          hintText: "请输入",
          maxZHCharLimit: 8,
        ),
        SizedBox(height: 15),
        //企业单位全称
        _EditTextWithTitleWidget(
          controller: _companyNameEditingController,
          title: "${registrationType ?? "企业"}全称",
          hintText: "选填",
          maxZHCharLimit: 30,
        ),
        SizedBox(height: 15),
        //所在城市
        _EditTextWithTitleWidget(
          controller: _locationEditingController,
          title: "所在区县",
          hintText: "请选择",
          isShowGoIcon: true,
          toJumpCallback: () async {

            HudUtils.showLoading(context,true);
            LocationRepository.getInstance().init(callback: (success)async{
              HudUtils.showLoading(context,false);
              Map<String, ChooseCityListItemBean> result =
              await ChooseCityPage.navigatorPush(context,
                  subLevel: 3, selected: _resultLocationMap);
              if (result == null || result.isEmpty) {
                return;
              }
              _resultLocationMap = result;
              _setLocationEditingValue();
            });


          },
        ),
        SizedBox(height: 15),
        //详细地址
        _EditTextWithTitleWidget(
          controller: _detailAddressEditingController,
          title: "详细地址",
          hintText: "请输入",
          maxZHCharLimit: 30,
        ),
        SizedBox(height: 20),
        _EditWithFrameWidget(
          controller: _nameEditingController,
          hintText: "姓名或称呼",
          maxZHCharLimit: 10,
          isNumber: false,
        ),
        SizedBox(height: 15),
        _EditWithFrameWidget(
          controller: _phoneEditingController,
          hintText: "手机号码",
          maxNumberLimit: DEFAULT_PHONE_LENGTH_LIMIT,
          maxZHCharLimit: DEFAULT_PHONE_LENGTH_LIMIT,
          isNumber: true,
        ),
        SizedBox(height: 15),
        _EditWithFrameWidget(
          controller: _authCodeEditingController,
          hintText: "验证码",
          isNumber: true,
          maxNumberLimit: DEFAULT_AUTH_LENGTH_LIMIT,
          maxZHCharLimit: DEFAULT_AUTH_LENGTH_LIMIT,
          rightWidget: CompanyRegisterSmsCodeWidget(
            phoneFunc: ()=> _phoneEditingController?.text?.trim(),
          ),
        ),
        SizedBox(height: 15)
      ],
    );
  }

  void _setLocationEditingValue() {
    _locationEditingController?.text = _getAddressStr();
  }

  String _getAddressStr() {
    if (_resultLocationMap == null || _resultLocationMap.isEmpty) {
      return null;
    }
    String province = _resultLocationMap[CHOOSE_PROVINCE_KEY]?.sname;
    String city = _resultLocationMap[CHOOSE_CITY_KEY]?.sname;
    String dirstrict = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.sname;
    if(StringUtils.isEmpty(dirstrict)){
      dirstrict = "";
    }
    if (province == city) {
      return "$province$dirstrict";
    } else {
      return "$province$city$dirstrict";
    }
  }

  String _getGpsStr() {
    if (_resultLocationMap == null || _resultLocationMap.isEmpty) {
      return null;
    }
    double   latitude = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.latitude;
    double   longitude = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.longitude;
    return AddressAboutUtils.getLongitudeAndLatitude(longitude?.toString(), latitude?.toString());
  }
}

/// 带标题的编辑框
///
/// @author: zengxiangxi
/// @createTime: 1/5/21 2:29 PM
/// @specialDemand:
class _EditTextWithTitleWidget extends StatefulWidget {
  final String title;

  final String hintText;

  final bool isShowGoIcon;

  final VoidCallback toJumpCallback;

  final TextEditingController controller;

  final int maxZHCharLimit;

  const _EditTextWithTitleWidget(
      {Key key,
      this.title,
      this.hintText,
      this.isShowGoIcon = false,
      this.toJumpCallback,
      this.controller, this.maxZHCharLimit})
      : super(key: key);

  @override
  _EditTextWithTitleWidgetState createState() =>
      _EditTextWithTitleWidgetState();
}

class _EditTextWithTitleWidgetState extends State<_EditTextWithTitleWidget> {
  FocusNode _focusNode;

  ValueNotifier<bool> _isShowFocusLineNotifier;

  @override
  void initState() {
    super.initState();
    _isShowFocusLineNotifier = ValueNotifier(false);
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_focusNode?.hasFocus ?? false) {
        _isShowFocusLineNotifier.value = true;
      } else {
        _isShowFocusLineNotifier.value = false;
      }
    });
  }

  @override
  void dispose() {
    _focusNode?.dispose();
    _isShowFocusLineNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Container(
          height: 45,
          child: Row(
            children: <Widget>[
              Container(
                width: 75,
                alignment: Alignment.centerLeft,
                child: Text(
                  widget.title ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getTextMinorGreyColor_808388(),
                    fontSize: 14,
                  ),
                ),
              ),
              Expanded(
                child: VgTextField(
                  controller: widget?.controller,
                  maxLines: 1,
                  focusNode: _focusNode,
                  readOnly: widget.toJumpCallback != null ? true : false,
                  onTap: () {
                    if (widget.toJumpCallback != null) {
                      widget.toJumpCallback();
                    }
                  },
                  maxLimitLength: widget?.maxZHCharLimit,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    counterText: "",
                    contentPadding: const EdgeInsets.only(bottom: 2),
                    hintText: widget.hintText ?? "",
                    hintStyle: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 14),
                  ),
                  style: TextStyle(
                      fontSize: 14,
                      color: ThemeRepository.getInstance()
                          .getTextMainColor_D0E0F7()),
                ),
              ),
              Opacity(
                opacity: widget.isShowGoIcon ? 1 : 0,
                child: Container(
                    padding: const EdgeInsets.only(left: 5),
                    child: Image.asset(
                      "images/go_ico.png",
                      width: 6,
                    )),
              )
            ],
          ),
        ),
        ValueListenableBuilder(
          builder: (_, value, Widget child) {
            return AnimatedContainer(
              height: 1,
              duration: DEFAULT_ANIM_DURATION,
              color: value
                  ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  : Color(0xFF303546),
            );
          },
          valueListenable: _isShowFocusLineNotifier,
        )
      ],
    );
  }
}

/// 带框的编辑框
///
/// @author: zengxiangxi
/// @createTime: 1/5/21 3:32 PM
/// @specialDemand:
class _EditWithFrameWidget extends StatelessWidget {
  final String hintText;

  final Widget rightWidget;

  final TextEditingController controller;

  final bool isNumber;

  final int maxZHCharLimit;

  final int maxNumberLimit;

  const _EditWithFrameWidget(
      {Key key,
      this.hintText,
      this.rightWidget,
      this.controller,
      this.isNumber = false,
      this.maxZHCharLimit,
      this.maxNumberLimit})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 45,
      decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          borderRadius: BorderRadius.circular(4)),
      child: Row(
        children: <Widget>[
          SizedBox(
            width: 15,
          ),
          Expanded(
            child: VgTextField(
              maxLines: 1,
              controller: controller,
              maxLimitLength: maxZHCharLimit,
              keyboardType: isNumber ? TextInputType.number : null,
              inputFormatters: isNumber
                  ? [
                      WhitelistingTextInputFormatter(RegExp("[0-9+]")),
                      maxNumberLimit != null
                          ? LengthLimitingTextInputFormatter(maxNumberLimit)
                          : null
                    ]
                  : null,
              decoration: InputDecoration(
                border: InputBorder.none,
                counterText: "",
                contentPadding: const EdgeInsets.only(bottom: 2),
                hintText: hintText ?? "",
                hintStyle: TextStyle(
                    color: VgColors.INPUT_BG_COLOR,
                    fontSize: 14),
              ),
              style: TextStyle(
                  fontSize: 14,
                  color:
                      ThemeRepository.getInstance().getTextMainColor_D0E0F7()),
            ),
          ),
          rightWidget ?? SizedBox(width: 15)
        ],
      ),
    );
  }
}
